package logparser.bean;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ParserSystem extends Parser implements IParser{
	private File m_outputFile;
	private DataOutputStream m_writer; 
	
	
	public String toCSVFormat(ParserLine parse){
		StringBuilder sb = new StringBuilder()
							.append(parse.getDate())
							.append(",")
							.append(parse.getLoglevel())
							.append(",")
							.append(csvHandlerStr(parse.getTag()))
							.append(",")
							.append(parse.getProcessId())
							.append(",")
							.append(parse.getProcessName())
							.append(",")
							.append(csvHandlerStr(parse.getMsg()))
							.append(",")
							.append(parse.getOrigLine())
							.append("\n");
		return sb.toString();
	}
	
	public String toCSVHead(){
		StringBuilder sb = new StringBuilder()
					.append("time")
					.append(",")
					.append("level")
					.append(",")
					.append("tag")
					.append(",")
					.append("pid")
					.append(",")
					.append("process name")
					.append(",")
					.append("content")
					.append(",")
					.append("origline")
					.append("\n");
		return sb.toString();
	}
	
	
	@Override
	public void processStart() throws Exception{
		// TODO Auto-generated method stub
		m_outputFile = new File(m_output_folder + File.separator + "android.csv");
		m_writer = new DataOutputStream(new FileOutputStream(m_outputFile));
		m_writer.write(utf8Head);
		CaptureSave.writeUTF8String(m_writer, toCSVHead());
	}

	@Override
	public void processEnd() {
		// TODO Auto-generated method stub
		try {
			m_writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public boolean processLine(String line, ParserLine parse) {
		// TODO Auto-generated method stub
		try {
			CaptureSave.writeUTF8String(m_writer, toCSVFormat(parse));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return true;
	}
	
}
